import axios from "axios";
import Cookies from "js-cookie";
import { Notification, Message } from "element-ui";

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const serviceForm = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_FORM_API,
  // 超时
  timeout: 10000
});

//添加请求拦截器(解决ajax重复提交的问题)
serviceForm.interceptors.request.use(
  config => {
    config.headers.Authorization =
      "Bearer " + Cookies.get("CUSTOM-REQUEST-HEADER");
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
serviceForm.interceptors.response.use(
  res => {
    // 未设置状态码则默认成功状态
    const code =
      (res.data.code || res.data.status || 200) == "0000_0"
        ? 200
        : res.data.code || res.data.status || 200;
    // 获取错误信息
    const message = res.data.message || res.data.msg;
    if (code === 500) {
      Message({
        message: message,
        type: "error"
      });
      return Promise.reject(new Error(message));
    } else if (code === 501 || code === 503) {
      Message({
        message: res.data.message,
        type: "error"
      });
      return Promise.reject(new Error(res.data.message));
    } else if (code == 1) {
      Message({
        message: message,
        //message: error.response.data.message,
        type: "error",
        duration: 5 * 1000
      });
    } else if (code !== 200) {
      Notification.error({
        title: message
      });
      return Promise.reject("error");
    } else {
      return JSON.parse(JSON.stringify(res.data));
    }
  },
  error => {
    if (undefined == error.response) {
      return false;
    }
    // if (error.response.config && 'string' != typeof (error.response.config) && error.response.config.method === 'post') {
    //   removePending(error.response.config)
    // }
    var message = error.response.data.message;
    if (undefined == error.response.data.status) {
      message = "数据异常，请稍后再试！";
    }
    Message({
      message: message,
      //message: error.response.data.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(message);
  }
);

export default serviceForm;
